;
(function() {
  var Edit = window.wangEditor
  var editor = new Edit('#editor')
  editor.customConfig.zIndex = 100
  editor.customConfig.uploadImgServer = uploadUrl
  editor.customConfig.uploadFileName = 'file'
  editor.customConfig.customAlert = function(info) {}
  editor.customConfig.uploadImgHooks = {
    // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
    // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
    customInsert: function(insertImg, result, editor) {
      // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
      // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果
      // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
      var url = result.url
      insertImg(url)
    }
  }

  // editor.txt.html()  读取内容
  // editor.txt.html('<p>用 JS 设置的内容</p>')   设置内容

  new Vue({
    el: '#cEnd-create',
    data: {
      flag: false,
      isImage: ['.jpg', '.jpeg', '.gif', '.png', '.bmp'],
      files: [],
      stateList: [],
      modulesList: [],
      moduleId: '',
      articleTitle: '',
      abstract: '',
      listImg: '',
      memo: '',
      status: '',
      // 2019-1-29 begin
      participateLt: [{
        name: '是',
        code: 'Y'
      }, {
        name: '否',
        code: 'N'
      }],
      participateAt: 'Y',
      dateTime: {
        begin: '',
        end: '',
        isDefalut: false
      },
      buttonName: '',
      moduleLt: [],
      fieldLt: [],
      isValidateLt: [{
        name: '是',
        code: true
      }, {
        name: '否',
        code: false
      }],
      moudleIndex: null,
      // 2019-1-29 end,
      isShowTemplate: false, //是否显示提交模板

      validList: [{
          key: 'Y',
          name: '启用'
        },
        {
          key: 'N',
          name: '停用'
        }
      ],
      module_code: '',
      seq: '',
      service_name: '',
      phone: '',
      weixin: '',
      attachment_names: '',
      attachment_urls: '',
      valid: '',
      entryType: '',
      uploadPercent: '',
      progress: '',
    },
    methods: {
      getServiceItem() {
        hlhttp.get({
          url: 'jwk/park_service',
          data: {
            'park_service_id': hlUrlUtil.GetQueryString('id')
          },
          success: (data) => {
            this.modulesList.some(item => {
              if (item.dictCode == data.moduleCode) {
                this.$refs.modelName.innerText = item.dictName
              }
            })
            if (data.valid == 'Y') {
              this.$refs.statusText.innerText = '启用'

            } else {
              this.$refs.statusText.innerText = '停用'
            }
            this.valid = data.valid
            this.module_code = data.moduleCode
            // this.seq = data.seq
            this.service_name = data.serviceName
            this.weixin = data.weixin
            this.phone = data.phone
            editor.txt.html(data.content)
            for (var i = 0; i < data.attachmentNames.length; i++) {
              this.files.push({
                name: data.attachmentNames[i],
                url: data.attachmentUrls[i]
              })
            }
          }
        })
      },
      //文件上传click()触发
      fileUp() {
        if (this.progress) {
          hl.toast('文件尚未上传完成')
          return
        }
        $('.fileButton').trigger('click')
      },
      fileToClick() {
        var that = this
        fileUpload('.fileButton', uploadUrl, (data) => {
          let type = data.json.name.substr(data.json.name.lastIndexOf('.'))
          if (this.isImage.indexOf(type) > -1) {
            this.files.push({
              name: data.json.name,
              url: data.json.url,
              type: 'pic'
            })
          }
          if (this.isImage.indexOf(type) == -1) {
            this.files.push({
              name: data.json.name,
              url: data.json.url,
              type: 'file'
            })
          }
        }, function(val) {
          that.progress = parseInt((val.loaded / val.total) * 100) + '%'
        })
      },
      // 获取文件上传进度
      getProgress() {
        hlhttp.get({
          baseUrl: exclUrl,
          url: 'resource/upload_rate_progress',
          success: (data) => {
            this.uploadPercent = data.uploadPercent
          }
        })
      },
      //图片上传click()触发
      picUp() {
        $('.picButton').trigger('click')
      },
      picToClick() {
        var that = this
        imgupload('.picButton', uploadUrl, (data) => {
          this.listImg = data.json.url
        })
      },
      //删除指定附件
      delFile(index) {
        this.files.splice(index, 1)
      },
      //模块列表获取
      getmodules() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'CSTM_JWK',
            config_name: 'CSTM_JWK_PARK_SERVICE_TYPE'
          },
          success: (data) => {
            this.modulesList = data
            if (this.entryType == 'edit') {
              this.getServiceItem()
            }
          }
        })
      },
      //获取模块id
      eventModule(code) {
        this.module_code = code
      },
      //获取状态
      eventStatus(key) {
        this.valid = key
      },
      validateInfo() {
        if (!this.module_code) {
          hl.toast('请选择所属模块')
          return false
        }
        if (!this.service_name) {
          hl.toast('请填写服务名称')
          return false
        }
        if (!this.phone) {
          hl.toast('请填写电话')
          return false
        }
        if (!this.weixin) {
          hl.toast('请填写微信')
          return false
        }
        if (!editor.txt.html().length) {
          hl.toast('请填写内容详情')
          return false
        }
        if (!this.valid) {
          hl.toast('请选择状态')
          return false
        }
        return true
      },
      //保存
      saveSubmit() {
        if (!this.validateInfo()) {
          return
        };
        let url = [],
          name = [];
        this.files.map(item => {
          url.push(item.url)
          name.push(item.name)
        })
        if (this.entryType == 'edit') {
          hlhttp.put({
            url: 'jwk/park_service',
            data: {
              park_service_id: hlUrlUtil.GetQueryString('id'),
              module_code: this.module_code,
              seq: '#',
              service_name: this.service_name,
              phone: this.phone,
              weixin: this.weixin,
              content: editor.txt.html(),
              attachment_urls: url.toString() || '#',
              attachment_names: name.toString() || '#',
              valid: this.valid,
            },
            success: (data) => {
              hlUrlUtil.goTo('jwkParkService', { ddtab: true }, true)
            }
          })
        } else {
          hlhttp.post({
            url: 'jwk/park_service',
            data: {
              module_code: this.module_code,
              seq: '#',
              service_name: this.service_name,
              phone: this.phone,
              weixin: this.weixin,
              content: editor.txt.html(),
              attachment_urls: url.toString() || '#',
              attachment_names: name.toString() || '#',
              valid: this.valid,
            },
            success: (data) => {
              hlUrlUtil.goTo('jwkParkService',{ddtab:true}, true)
            }
          })
        }
      },
      //预览
      previewInfo() {
        if (!this.validateInfo()) {
          return
        };
        let data = {
          title: this.service_name,
          content: editor.txt.html(),
          files: this.files,
        }
        window.sessionStorage.setItem('previewInfo', JSON.stringify(data))
        hlUrlUtil.goTo('jwkpreviewService', { ddtab: true }, true)
      }
    },
    created() {
      hlSelectUi()
    },
    mounted() {
      editor.create()
      this.fileToClick()
      this.picToClick()
      this.getmodules()
      this.entryType = hlUrlUtil.GetQueryString('type')
    }
  })
}())
